package org.je.log;

import org.je.io.file.FileWriter;

/**
 * @author fanyifeng
 */
class LogBuffer
{
	private final byte[]	logBuffer	= new byte[1024 * 8];
	private volatile int	offset		= 0;
	private final Object	bufferLock	= new Object();
	private final String	logFilePath;

	LogBuffer(String path) {
		this.logFilePath = path;
	}

	void save(byte[] data) {
		synchronized(bufferLock) {
			if (offset + data.length < logBuffer.length) {
				System.arraycopy(data, 0, logBuffer, offset, data.length);
				offset += data.length;
			} else {
				byte[] writeData = new byte[data.length + offset];
				System.arraycopy(logBuffer, 0, writeData, 0, offset);
				System.arraycopy(data, 0, writeData, offset, data.length);
				FileWriter.append(logFilePath, writeData);
				offset = 0;
			}
		}
	}

	void clearBuffer() {
		if (offset == 0)
			return;
		synchronized(bufferLock) {
			byte[] tem = new byte[offset];
			System.arraycopy(logBuffer, 0, tem, 0, offset);
			offset = 0;
			FileWriter.append(logFilePath, tem);
		}
	}
}
